var app = getApp()

var detect = function (imageData) {
  return new Promise(function (resolve, reject) {
    var token = app.globalData.token
    tt.request({
      url: "https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=" + token,
      method: "POST",
      header: {
        "content-type": "application/json"
      },
      data: {
        version: '1.0',
        image: imageData,
        image_type: "BASE64",
      },
      success: function (res) {
        console.log("人脸检测==" + JSON.stringify(res))
        var data = res.data
        if (!data.error_code || data.error_code == 0) {
          if (data.result.face_list && data.result.face_list.length > 0) {
            var location = data.result.face_list[0].location
            resolve({
              image: imageData,
              location: location
            })
          }
        } else {
          reject("人脸检测失败");
        }
      },
      fail: function (e) {
        reject(e);
      }
    });
  });
}
var checkBaiduImg = function (imageData) {
  return new Promise(function (resolve, reject) {
    var token = app.globalData.accessToken
    wx.request({
      url: "https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined?access_token=" + token,
      method: "POST",
      header: {
        "content-type": "application/x-www-form-urlencoded",
      },
      data: {
        image: imageData
      },
      success: function (res) {
        console.log("res=====" + JSON.stringify(res))
        if (res.data.conclusionType == 1) {
          resolve(imageData)
        } else {
          console.log("违规图片====" , JSON.stringify(res))
          reject("违规图片")
        }
      },
      fail: function (e) {
        console.log("fail--checkImg====" , JSON.stringify(e))
        reject(e);
      }
    });
  });
}
function localImageTobase64(path) {
  return new Promise(function (resolve, reject) {
    wx.getFileSystemManager().readFile({
      filePath: path,
      encoding: "base64",
      success: function (res) {
        console.log("localImageTobase64=",res)
        resolve(res.data);
      },
      fail: function (res) {
        console.log("localImageTobase64 fail===", res)
        reject(res);
      }
    });
  });
}
module.exports = {
  detect: detect,
  checkBaiduImg: checkBaiduImg,
  localImageTobase64:localImageTobase64
}